/********************************************
 * 功能说明: 
 * 模块名称: 
 * 系统名称: 
 * 软件版权: Frank
 * 系统版本: 1.0.0
 * 开发人员: Frank
 * 开发时间: 2019/9/19 17:04
 * 审核人员: 
 * 相关文档: 
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.job.web.converter;

import com.spring.arch.job.common.errorcode.JobErrorCode;
import com.spring.arch.job.dto.JobParam;
import com.spring.arch.job.model.JobInfo;
import com.spring.arch.job.web.dto.JobInfoPersistableDTO;
import com.spring.arch.common.exception.ExceptionHolder;
import com.spring.arch.job.dto.JobParam;
import com.spring.arch.job.model.JobInfo;
import com.spring.arch.job.web.dto.JobInfoPersistableDTO;
import lombok.NonNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

import static com.spring.arch.job.common.errorcode.JobErrorCode.E1015001001;

/**
 * 任务信息转换器
 * @author Frank
 * @version 1.0.0.1
 * @since JDK 1.8
 */
@Component
public class JobInfoConverter {

    public JobInfo toModel(@NonNull final JobInfoPersistableDTO dto) {
        JobInfo model = new JobInfo();
        BeanUtils.copyProperties(dto, model);
        return model;
    }

    public JobInfo jobParamToModel(@NonNull final JobParam param) {
        JobInfo model = new JobInfo();
        model.setJobGroup(param.getJobGroup());
        model.setJobCron(param.getJobCron());
        model.setJobDesc(param.getJobDesc());
        model.setAddTime(LocalDateTime.now());
        model.setAuthor("SYSTEM");
        model.setExecutorRouteStrategy(param.getExecutorRouteStrategy());
        model.setExecutorHandler(param.getExecutorHandler());
        model.setExecutorParam(param.getExecutorParam());
        model.setExecutorBlockStrategy(param.getExecutorBlockStrategy());
        model.setExecutorTimeout(param.getExecutorTimeout());
        model.setExecutorFailRetryCount(param.getExecutorFailRetryCount());
        model.setGlueType(param.getGlueType());
        model.setGlueRemark("GLUE代码初始化");
        model.setGlueUpdateTime(LocalDateTime.now());
        model.setTriggerStatus(1); //默认启动
        return model;
    }

    public JobInfoPersistableDTO toDTO(@NonNull final JobInfo model) {
        JobInfoPersistableDTO dto = new JobInfoPersistableDTO();
        BeanUtils.copyProperties(model, dto);
        return dto;
    }

    /**
     * job参数转成jobInfo集合
     * @param jobParams job参数
     * @return jobInfo集合
     */
    public List<JobInfo> jobParamsToModelList(List<JobParam> jobParams) {
        if (CollectionUtils.isEmpty(jobParams)) {
            throw ExceptionHolder.serviceException(JobErrorCode.E1015001001);
        }
        return jobParams.stream().map(this::jobParamToModel).collect(Collectors.toList());
    }
}
